/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.news;

import com.blandware.atleap.common.NewsModuleConstants;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.model.news.NewsItem;
import com.blandware.atleap.service.news.NewsManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.news.NewsItemForm;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.news.NewsModuleWebConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Show news item to customer
 * </p>
 * <p><a href="ShowNewsItemAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.16 $ $Date: 2008/04/29 17:51:52 $
 * @struts.action path="/news/showItem"
 * name="newsItemForm"
 * scope="request"
 * validate="false"
 * @struts.action-forward name="viewNewsItem"
 * path=".news.showItem"
 * @struts.action-forward name="listNewsItems"
 * path="/news/listItems.do"
 * redirect="true"
 */
public final class ShowNewsItemAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {
		NewsItemForm newsItemForm = (NewsItemForm) form;
		Long newsItemId = null;
		if ( !GenericValidator.isBlankOrNull(newsItemForm.getId()) ) {
			newsItemId = Long.valueOf(newsItemForm.getId());
		} else if ( request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_ID_KEY) != null ) {
			newsItemId = (Long) request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_ID_KEY);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing news item ID. Returning to list...");
			}
			return mapping.findForward("listNewsItems");
		}

		NewsManager newsManager = (NewsManager) getBean(NewsModuleConstants.NEWS_MANAGER_BEAN);
		NewsItem newsItem = newsManager.retrieveNewsItem(newsItemId);
		if ( newsItem == null ) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		}

		if ( !newsItem.getActive().booleanValue() ) {
			response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
			return null;
		}

		// check user role
        List itemRoles = newsItem.getRoles();
        if ( itemRoles != null && !itemRoles.isEmpty() ) {
            boolean isUserInRole = false;
            for ( Iterator i = itemRoles.iterator(); i.hasNext(); ) {
                Role role = (Role) i.next();
                isUserInRole = isUserInRole || request.isUserInRole(role.getName());
            }

            if ( !isUserInRole ) {
                // access denied
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return null;
            }
        }

        request.setAttribute(WebappConstants.DISPLAYED_OBJECT_URI_KEY,
                             newsItem.getUri());

		request.setAttribute("newsItem", newsItem);
		return mapping.findForward("viewNewsItem");
	}
}